package com.wmz.aiagent.advisors;

import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.ai.chat.client.advisor.api.*;
import org.springframework.ai.chat.model.MessageAggregator;
import reactor.core.publisher.Flux;

/**
 * 自定义日志Advisor
 * 打印info级别日志，只输出单次用户提示词和AI 回复的文本
 */
@Slf4j
public class MyLoggerAdvisor implements CallAroundAdvisor, StreamAroundAdvisor {

	private static final Logger logger = LoggerFactory.getLogger(MyLoggerAdvisor.class);

	@Override
	public String getName() {
		return this.getClass().getSimpleName();
	}

	@Override
	public int getOrder() {
		return 0;
	}

	/**
	 * 前置处理器
	 * @param request
	 * @return
	 */
	private AdvisedRequest before(AdvisedRequest request) {
		log.info("AI Request:{}",request.userText());
		return request;
	}

	/**
	 * 后置处理器
	 * @param response
	 */
	private void observeAfter(AdvisedResponse response) {
		log.info("AI Response:{}",response.response().getResult().getOutput().getText());
	}

	@Override
	public AdvisedResponse aroundCall(AdvisedRequest advisedRequest, CallAroundAdvisorChain chain) {
		advisedRequest = this.before(advisedRequest);
		// 更新上下文：可以使用adviseContext在Advisor链中共享状态，类似threadLocal。
		/* advisedRequest = advisedRequest.updateContext(context -> {
			context.put("key", "value");
			return context;
		});*/
		AdvisedResponse advisedResponse = chain.nextAroundCall(advisedRequest);
		this.observeAfter(advisedResponse);
		return advisedResponse;
	}

	@Override
	public Flux<AdvisedResponse> aroundStream(AdvisedRequest advisedRequest, StreamAroundAdvisorChain chain) {

		advisedRequest = this.before(advisedRequest);

		Flux<AdvisedResponse> advisedResponses = chain.nextAroundStream(advisedRequest);

        return new MessageAggregator().aggregateAdvisedResponse(advisedResponses, this::observeAfter);
	}


}